package com.ddtech.business.config;

import com.alibaba.fastjson.JSONObject;
import com.ddtech.business.room.dto.OnSystemUser;
import com.ddtech.business.room.entity.Room;
import com.ddtech.business.room.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @ClassName:WebSocketTask description：
 * @author:wei_zhang(xiao)
 * @date: 2024-12-11 15:04
 */
@Component
@Slf4j
@EnableScheduling
public class WebSocketTask {

   // private static final Logger logger = LoggerFactory.getLogger(WebSocketTask.class);

    @Autowired
    private RoomService roomService;

    @Value("${jwt.onSystem}")
    private String onSystemKey;

    private final RedisTemplate redisTemplate;

    public WebSocketTask(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * description: 10秒进行一次心跳检测
     * @param:  * @param
     * @date: 2024-12-11
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
   @Scheduled(cron = "0/8 * * * * ?")
    public void clearOrders() {
        // 有在线人数用户，才去查询房间数据
//        JSONObject json = new JSONObject();
//        json.put("type", WebsocketConstant.HEART_MESSAGE);
//        json.put("data","ping");
//        List<String> ls  = WebSocketRoomServer.sendPing(json.toString());
//        if(ls!=null && ls.size()>0){
//            List<Room> list =roomService.list();
//            for(Room room : list){
//                if(ls.contains(room.getCreateUserId())){
//                    roomService.removeById(room.getId());
//                }
//            }
//        }
        List<String> listUserList =new ArrayList<>();
        Map<String, LocalDateTime> heartList= WebSocketRoomServer.heartList;
        if (heartList!=null && heartList.size()>0){
            for (Map.Entry<String, LocalDateTime> entry : heartList.entrySet()) {
                LocalDateTime localDateTime =LocalDateTime.now();
                long secondDiff = ChronoUnit.SECONDS.between(entry.getValue(), localDateTime);
                if(secondDiff>5){
                    //已断线用户
                    listUserList.add(entry.getKey());
                    //移除断线用户
                    heartList.remove(entry.getKey());
                    //清除在线人数
                    redisTemplate.delete(onSystemKey + entry.getKey());
                    //断开与客户端的
                    Map<String, WebSocketRoomServer> webSocketMap =WebSocketRoomServer.webSocketMap;
                    if (webSocketMap.containsKey(entry.getKey())) {
                        webSocketMap.remove(entry.getKey());
                    }
                }
            }
            if(listUserList.size()>0){
                //发送在线人数消息
                JSONObject json = new JSONObject();
                json.put("type", WebsocketConstant.TRAIN_MESSAGE);
                json.put("data",this.getOnSystemUser());
                WebSocketOnLineServer.sendInfo(json.toString());
                List<Room> list =roomService.list();
                for(Room room : list){
                    if (listUserList.contains(room.getCreateUserId())){
                        roomService.removeById(room.getId());
                        //logger.info("断线删除的房间id"+room.getId());
                    }
                }
            }
        }
    }

    public int getOnSystemUser() {
        List<String> keys = new ArrayList<>(redisTemplate.keys(onSystemKey + "*"));
        Collections.reverse(keys);
        List<OnSystemUser> onlineUsers = new ArrayList<>();
        for (String key : keys) {
            OnSystemUser onSystemUser = (OnSystemUser) redisTemplate.opsForValue().get(key);
            onlineUsers.add(onSystemUser);
        }
        if (onlineUsers!=null && onlineUsers.size()>0){
            return onlineUsers.size();
        }
        return 0;
    }

    @PostConstruct
    public void clearRoomData(){
        List<Room> list =roomService.list();
        if (list!=null && list.size()>0){
            for(Room room : list){
                roomService.removeById(room.getId());
            }
        }
    }
}
